package com.wang.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wang.auth.service.SysLoginLogService;
import com.wang.auth.service.SysMenuService;
import com.wang.auth.service.SysUserService;
import com.wang.common.config.exception.CustomException;
import com.wang.common.result.Result;
import com.wang.common.utils.JwtHelper;
import com.wang.common.utils.MD5;
import com.wang.model.system.SysLoginLog;
import com.wang.model.system.SysUser;
import com.wang.model.system.vo.LoginVo;
import com.wang.model.system.vo.RouterVo;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author wjh
 * @create 2023-04-18
 */
@Api(tags = "后台登录管理")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysMenuService menuService;

    @Autowired
    private SysLoginLogService loginLogService;
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo, HttpServletRequest request){
//        {"code":20000,"data":{"token":"admin-token"}}
//        HashMap<String, Object> hashMap = new HashMap<>();
//        hashMap.put("token","admin-token");
//        return Result.success(hashMap);
        System.out.println(loginVo);
        String username = loginVo.getUsername();
        String password = MD5.encrypt(loginVo.getPassword());
        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //isNotEmpty等价于 a != null && a.length > 0
        //isNotBlank 等价于 a != null && a.length > 0 && str.trim().length > 0
        //isNotEmpty把空格当字符串，isNotBlank把空格不当字符串
        sysUserLambdaQueryWrapper.eq(StringUtils.isNotEmpty(username),SysUser::getUsername,username);
        SysUser user = userService.getOne(sysUserLambdaQueryWrapper);
        if (user == null){
            throw new CustomException(201,"用户不存在");
        }
        String password_db = user.getPassword();
        System.out.println(password_db);
        if (!password_db.equals(password)){
            throw new CustomException(201,"密码错误！");
        }
        if (user.getStatus() == 0){
            throw new CustomException(201,"用户已被禁用！");
        }
        String token = JwtHelper.createToken(user.getId(), username);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);


        return Result.success(map);
    }

    //检查ip存在

    @GetMapping("/info")
    public Result info(HttpServletRequest request){
        //从请求头获取用户token
        String header = request.getHeader("token");
        System.out.println(header);
        //从token中获取用户id和username
        Long userId = JwtHelper.getUserId(header);
        if (userId == null){
            return Result.error("请求错误！");
        }
        String username = JwtHelper.getUsername(header);
        //从数据库中根据id查用户信息
        SysUser user = userService.getById(userId);
        //根据用户id获取用户可以操作的菜单和按钮
        List<RouterVo> menuList = menuService.findUserMenuListByUserId(userId);
        List<String> permsList =  menuService.findUserPermsByUserId(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("roles","[admin]");
        map.put("name",user.getName());
        map.put("avatar","https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
        //返回用户可以操作的菜单
        map.put("routers",menuList);
        //返回用户可以点击的按钮
        map.put("buttons",permsList);
        return Result.success(map);
    }

    /**
     * 退出
     * @return
     */
    @PostMapping("/logout")
    public Result logout(){
        return Result.success(null);
    }

}
